//
//  MainPageTopicTableView.swift
//  Gaoloumi
//
//  Created by Jasper on 4/9/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import UITableView_FDTemplateLayoutCell
import MJRefresh
import SVProgressHUD
import SDCycleScrollView
import AVOSCloud

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}


enum TopicType {
    case newTopic      // 最新
    case mostReply     // 最多回复
    case mostClick     // 最多点击
    case commendTopic  // 推荐
}

protocol MainPageTopicTableViewDelegate : NSObjectProtocol  {
    func mainPageTopicTableView(_ tableView:UITableView, object: AVObject)
    
}

class MainPageTopicTableView: UITableView, UITableViewDelegate, UITableViewDataSource, SDCycleScrollViewDelegate {

    weak var selectDelegate: MainPageTopicTableViewDelegate?
    
    var topicArray = [Topic]()
    var bannerArray = [Topic]()
    
    var topicType: TopicType = .newTopic
    
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        self.delegate = self
        self.dataSource = self
        
        self.register(UINib(nibName: "MainPageTopicsCell", bundle: nil), forCellReuseIdentifier: "MainPageTopicsCell")
        
        self.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.requestData(true)
        })
        
        self.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.requestData(false)
        })
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
//        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: netRequest
    
    func requestData(_ header: Bool) {
        SVProgressHUD.show()
        let query: AVQuery = Topic.query()
        query.includeKey(kTopicKeyContentImage)
        query.includeKey(kTopicKeyUser)
        query.includeKey(kTopicKeyCitys)
        
        if topicType == .mostClick {
            query.order(byDescending: kTopicKeyClickCount) // 回复次数排序
            query.addDescendingOrder(kTopicKeyReplyCount)
//            query.orderByDescending(kTopicKeyReplyCount) // 回复次数排序
        } else if topicType == .mostReply {
            query.order(byDescending: kTopicKeyReplyCount) // 回复次数排序
            query.addDescendingOrder(kTopicKeyClickCount)
//            query.orderByDescending(kTopicKeyClickCount) // 回复次数排序
        } else if topicType == .commendTopic {
            query.whereKey(kTopicKeyIsCommend, equalTo: true)
        } else if topicType == .newTopic {
            query.order(byDescending: "createdAt")        // 创建时间排序
        }
        query.limit = kNetPageSize
        
        if !header {
            let top = topicArray.last
            if topicType == .newTopic {
                let date = top?.object(forKey: "createdAt")  // 这个时间需要下次优化，需考虑banner的时间
                if date != nil {
                    query.whereKey("createdAt", lessThan: date)
                } else {
                    query.whereKey("createdAt", lessThan: Date())
                }
            } else if topicType == .mostClick {
                let clickedCount = top?.clickCount
                query.whereKey(kTopicKeyClickCount, lessThanOrEqualTo: clickedCount)
                query.whereKey(kTopicKeyReplyCount, lessThanOrEqualTo: top?.replyCount)
            } else if topicType == .mostReply {
                let replyCount = top?.replyCount
                query.whereKey(kTopicKeyReplyCount, lessThanOrEqualTo: replyCount)
                query.whereKey(kTopicKeyClickCount, lessThanOrEqualTo: top?.clickCount)
            }
        }
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
            self.resolveObject(objects, error: error, header: header)
        }
    }
    
    func resolveObject(_ objects: [Any]?, error: Error?, header: Bool) {
        if error == nil && objects != nil {
            if let topic = objects as? [Topic] {
                if header {
                    self.topicArray.removeAll()
                    self.bannerArray.removeAll()
                }
                
                for top in topic {
                    if (top.contentImage?.count)! > 0 && self.bannerArray.count < 3 {
                        self.bannerArray.append(top)
                    } else {
                        if self.topicArray.contains(top) {  // 去重逻辑
                            continue
                        }
                        self.topicArray.append(top)
                    }
                }
                
                //                    self.topicArray += topic
                self.reloadData()
                SVProgressHUD.dismiss()
            } else {
                SVProgressHUD.showError(withStatus: "获取列表失败")
            }
        } else {
            SVProgressHUD.showError(withStatus: error?.localizedDescription)
        }
        self.mj_header.endRefreshing()
        if objects != nil && objects?.count < kNetPageSize {
            self.mj_footer.endRefreshingWithNoMoreData()
        } else {
            if header {
                self.mj_footer.resetNoMoreData()
            } else {
                self.mj_footer.endRefreshing()
            }
        }
        
        if header {  // 只有上拉刷新才加载header
            let screenWidth = UIScreen.main.bounds.size.width
            let intScreenWidth = Int(screenWidth)
            if self.bannerArray.count > 0 {
                
                var imagesURLStrings = [String]()
                var titles = [String]()
                
                for banTop in self.bannerArray {
                    let urlstr = (banTop.contentImage?.first?.url)!
                    let urlCon = "\(urlstr)?imageView/1/w/\(intScreenWidth*2)/h/\(intScreenWidth)"
                    imagesURLStrings.append(urlCon)
                    titles.append(banTop.title!)
                }
                
                let banner = SDCycleScrollView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenWidth*2.5/6), delegate: self, placeholderImage: nil)
                banner?.pageControlAliment = SDCycleScrollViewPageContolAlimentRight
                banner?.imageURLStringsGroup = imagesURLStrings
                banner?.titlesGroup = titles
                banner?.currentPageDotColor = UIColor.mainColor() // 自定义分页控件小圆标颜色
                banner?.autoScrollTimeInterval = 5
                self.tableHeaderView = banner
            } else {
                self.tableHeaderView = nil;
            }
        }
    }
    
    // MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return topicArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: "MainPageTopicsCell", configuration: { (cell: Any?) in
            let mainCell = cell as? MainPageTopicsCell
            let topic = self.topicArray[(indexPath as NSIndexPath).row]
            mainCell?.refreshView(topic)
        })
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainPageTopicsCell", for: indexPath) as! MainPageTopicsCell
        cell.selectionStyle = .none
        let topic = topicArray[(indexPath as NSIndexPath).row]
        cell.refreshView(topic)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let topic = topicArray[(indexPath as NSIndexPath).row]
        selectDelegate?.mainPageTopicTableView(self, object: topic)
    }
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        let topic = bannerArray[index]
        selectDelegate?.mainPageTopicTableView(self, object: topic)
    }
}
